package com.example.test_witns.adapter.todoAdapter;

import static com.luck.picture.lib.thread.PictureThreadUtils.runOnUiThread;

import android.app.Activity;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.example.test_witns.R;
import com.example.test_witns.pojo.TodoTask;
import com.example.test_witns.ui.sheets.ModifyTaskBottomSheet;
import com.example.test_witns.ui.sheets.TaskBottomSheet;
import com.example.test_witns.ui.todo.TodoFragment;
import com.google.android.material.snackbar.Snackbar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TodoAdapter extends RecyclerView.Adapter<TodoAdapter.TaskViewHolder> {
    private static final Logger log = LoggerFactory.getLogger(TodoAdapter.class);
    private List<TodoTask> taskList;
    private OnTaskClickListener onTaskClickListener;
    private RecyclerView recyclerView;
    private TextView todo_all_done;
    private ImageView all_done_image_view;
    private TextView tv_progress;
    private Context context;
    public OnItemModifiedListener onItemModifiedListener;
    public OnItemDeletedListener onItemDeletedListener;
    public OnCompleteStatusChangedListener onCompleteStatusChangedListener;

    public interface OnItemModifiedListener{
        void onItemModified(TodoTask initialTask, TodoTask modifiedTask);
    }

    public interface OnItemDeletedListener{
        void onItemDeleted(TodoTask DeletedTask);
    }

    public interface OnCompleteStatusChangedListener{
        void onCompleted(long id);
        void onUncompleted(long id);
    }

    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public TodoAdapter(List<TodoTask> taskList, Context context) {
        this.taskList = taskList;
        this.context = context;
    }

    public void setOnTaskClickListener(OnTaskClickListener onTaskClickListener){
        this.onTaskClickListener = onTaskClickListener;
    }

    public interface OnTaskClickListener{
        void OnTaskClicked(TodoTask task, TaskBottomSheet bottomSheet);
    }

    @NonNull
    @Override
    public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_task, parent, false);
        return new TaskViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
        TodoTask todoTask = taskList.get(position);
        holder.bind(todoTask);
        // 绑定数据并设置动画
        setScaleAnimation(holder.itemView);

        scheduler.scheduleWithFixedDelay(() -> {
            LocalDateTime now = LocalDateTime.now();
            if (isDueTimePassed(todoTask.getDueDate(), todoTask.getDueTime()) && !todoTask.isCompleted()) {
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!todoTask.isCompleted()){
                            holder.is_completed_text_view.setTextColor(Color.RED);
                            holder.is_completed_text_view.setText("已超时 !!");
                        }
                    }
                });
            }
        }, 2, 2, TimeUnit.SECONDS);

        holder.cb_complete.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    todoTask.setCompleted(true);
                    onCompleteStatusChangedListener.onCompleted(todoTask.getId());
                }else {
                    todoTask.setCompleted(false);
                    onCompleteStatusChangedListener.onUncompleted(todoTask.getId());
                }

                if (todoTask.isCompleted()){
                    holder.is_completed_text_view.setText("已完成 !");
                    holder.is_completed_text_view.setTextColor(Color.parseColor("#00dd00"));
                    TodoFragment.finishedTask++;
                    String tv_progressString = "已完成 " + TodoFragment.finishedTask + "/" + taskList.size() +" 项";
                    tv_progress.setText(tv_progressString);
                }else {
                    holder.is_completed_text_view.setText("进行中");
                    holder.is_completed_text_view.setTextColor(Color.parseColor("#FA8C00"));
                    TodoFragment.finishedTask--;
                    String tv_progressString = "已完成 " + TodoFragment.finishedTask + "/" + taskList.size() +" 项";
                    tv_progress.setText(tv_progressString);
                }
            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TaskBottomSheet bottomSheet = TaskBottomSheet.newInstance(todoTask);
                bottomSheet.setOnTaskActionListener(new TaskBottomSheet.OnTaskActionListener() {
                    @Override
                    public void onEditTask(TodoTask task) {
                        for (TodoTask todoTask : taskList){
                            if (todoTask.getId() == task.getId()){
                                showModifyTaskDialog(todoTask);
                            }else {
                                log.debug("匹配失败");
                            }
                        }
                    }

                    @Override
                    public void onDeleteTask(TodoTask task) {
                        for (TodoTask todoTask : taskList){
                            if (todoTask.getId() == task.getId()){
                                int pos = taskList.indexOf(todoTask);
                                if (pos != -1) {
                                    onItemDeletedListener.onItemDeleted(todoTask);
                                } else {
                                    Toast.makeText(v.getContext(), "未匹配到任务", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }

                    }
                });
                onTaskClickListener.OnTaskClicked(todoTask, bottomSheet);
            }
        });
    }

    public void addTask(TodoTask task) {
        taskList.add(task); // 假设 taskList 是 RecyclerView 的数据源
        notifyItemInserted(taskList.size() - 1); // 通知 RecyclerView 更新
    }

    public void modifyTask(TodoTask initialTask, TodoTask modifiedTask){
        int position = taskList.indexOf(initialTask);
        runOnUiThread(() -> {
            taskList.remove(initialTask);
            taskList.add(position, modifiedTask); // 假设 taskList 是 RecyclerView 的数据源
            notifyItemChanged(position);
        });
    }

    public void removeAll(){
        taskList.clear();
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return taskList.size();
    }

    static class TaskViewHolder extends RecyclerView.ViewHolder {
        private TextView tv_title = itemView.findViewById(R.id.tv_title);
        private TextView tv_time = itemView.findViewById(R.id.tv_time);
        private ImageView iv_priority = itemView.findViewById(R.id.iv_priority);
        private TextView tv_category = itemView.findViewById(R.id.tv_category);
        private CheckBox cb_complete = itemView.findViewById(R.id.cb_complete);
        private TextView is_completed_text_view = itemView.findViewById(R.id.is_completed_text_view);
        // 绑定视图
        public TaskViewHolder(@NonNull View itemView) {
            super(itemView);
        }

        public void bind(TodoTask task) {
            tv_title.setText(task.getTitle());
            LocalDate today = LocalDate.now(); // 获取当前日期
            int year = today.getYear();
            String[] dueDate = task.getDueDate().split("-");
            if (String.valueOf(year).equals(dueDate[0])){
                String briefTime = dueDate[1] + "-" + dueDate[2] + " " + task.getDueTime();
                tv_time.setText(briefTime);
            }else {
                String fullTime = task.getDueDate() + task.getDueTime();
                tv_time.setText(fullTime);
            }
            tv_category.setText(task.getCategory());

            if (task.getPriority() > 100 && task.getPriority() < 201){
                iv_priority.setImageTintList(ColorStateList.valueOf(Color.parseColor("#FA8C00")));
            } else if (task.getPriority() < 101) {
                iv_priority.setImageTintList(ColorStateList.valueOf(Color.GREEN));
            }else {
                iv_priority.setImageTintList(ColorStateList.valueOf(Color.RED));
            }

            cb_complete.setChecked(task.isCompleted());

            if (task.isCompleted()){
                is_completed_text_view.setText("已完成 !");
                is_completed_text_view.setTextColor(Color.parseColor("#00dd00"));
            }else {
                is_completed_text_view.setText("进行中");
                is_completed_text_view.setTextColor(Color.parseColor("#FA8C00"));
            }

        }
    }

    private void setScaleAnimation(View view) {
        ScaleAnimation anim = new ScaleAnimation(
                0.8f, 1f, 0.8f, 1f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f
        );
        anim.setDuration(300);
        view.startAnimation(anim);
    }

    private void showUndoSnackbar(int position, View view) {
        TodoTask deletedTask = taskList.get(position);
        Snackbar snackbar = Snackbar.make(view, deletedTask.getTitle() + " 任务已删除", Snackbar.LENGTH_LONG);
        snackbar.setAction("撤销", v -> {
            taskList.add(position, deletedTask);
            notifyItemInserted(position);
        });
        snackbar.show();
    }

    public void setRecyclerView(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }

    public void setTodoAllDoneTextView(TextView todo_all_done) {
        this.todo_all_done = todo_all_done;
    }

    public void setTodoAllDoneImageView(ImageView all_done_image_view) {
        this.all_done_image_view = all_done_image_view;
    }

    public void setTv_progressTextView(TextView tv_progress) {
        this.tv_progress = tv_progress;
    }

    public static boolean isDueTimePassed(String dueDate, String dueTime) {
        // 定义日期和时间格式
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");

        // 解析截至日期和时间
        LocalDate dueDateLocal = LocalDate.parse(dueDate, dateFormatter);
        LocalTime dueTimeLocal = LocalTime.parse(dueTime, timeFormatter);

        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();

        // 将截至日期和时间组合为 LocalDateTime
        LocalDateTime dueDateTime = LocalDateTime.of(dueDateLocal, dueTimeLocal);

        // 比较当前时间与截至时间
        return dueDateTime.isBefore(now);
    }

    private void showModifyTaskDialog(TodoTask todoTask) {
        // 显示底部弹窗
        ModifyTaskBottomSheet bottomSheet = new ModifyTaskBottomSheet(todoTask);
        bottomSheet.setOnTaskModifiedListener(new ModifyTaskBottomSheet.OnTaskModifiedListener() {
            @Override
            public void onTaskModified(TodoTask initialTask, TodoTask modifiedTask) {
                onItemModifiedListener.onItemModified(modifiedTask, modifiedTask);
            }
        });
        bottomSheet.show(((FragmentActivity) context).getSupportFragmentManager(), bottomSheet.getTag());
    }

    public void setOnItemModifiedListener(OnItemModifiedListener onItemModifiedListener){
        this.onItemModifiedListener = onItemModifiedListener;
    }

    public void  setOnItemDeletedListener(OnItemDeletedListener onItemDeletedListener){
        this.onItemDeletedListener = onItemDeletedListener;
    }

    public void  setOnCompleteStatusChangedListener(OnCompleteStatusChangedListener onCompleteStatusChangedListener){
        this.onCompleteStatusChangedListener = onCompleteStatusChangedListener;
    }
}